//
//  SSHomeTableViewController.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/28.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class SSHomeTableViewController: SSBaseTableViewController {
    private let estimatedRowHeight: CGFloat = 100
    private enum SSStatusCellType: String {
        case normal = "normal"
        case retweet = "retweet"
    }
    private var statuses: [SSStatus]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        visitorView?.setupUIContent("visitordiscover_feed_image_house", hintLabelContent: "关注一些人，回这里看看有什么惊喜", isHome: true)
        if SSUserToken.loadToken() == nil {
            navigationItem.setLeftBarButtonItem(UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewWillRegister"), animated: true)
            navigationItem.setRightBarButtonItem(UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorViewWillLogin"), animated: true)
            return
        }

        prepareCell()
        prepareRefresh()
        loadData()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "triggerFotoBrowser:", name: SSStatusPicViewDidSelectedNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "shareRetweet:", name: SSStatusFooterViewRetweetButtonNotification, object: nil)
    }
    
    @objc private func shareRetweet(notify: NSNotification) {
        let status = notify.userInfo![SSStatusFooterViewStatus] as! SSStatus
        let presentStatus = status.retweeted_status == nil ? status : status.retweeted_status
        let shareText = presentStatus!.text
        var image: UIImage? = nil
        if presentStatus?.largePicURLS != nil {
            image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(presentStatus!.largePicURLS![0].absoluteString)
        }
        
        UMSocialSnsService.presentSnsIconSheetView(self, appKey: UMengAppKey, shareText: shareText, shareImage: image, shareToSnsNames: [UMShareToSina, UMShareToTencent, UMShareToRenren, UMShareToDouban], delegate: nil)
    }
    
    @objc private func triggerFotoBrowser(notify: NSNotification) {
        // 需要判断info
        
        guard let status = notify.userInfo![SSStatusPicViewStatus] else {
            return
        }
        guard let indexPath = notify.userInfo![SSStatusPicViewStatusDidSelectedIndexPath] else {
            return
        }
        guard let pictureView = notify.object as? SSStatusPicView else {
            return
        }
        picView = pictureView
        presentIndexPath = indexPath as? NSIndexPath
        let s = status as! SSStatus
        let selURL = s.picURLS![indexPath.item]
//        print(selURL)
        presentView.sd_setImageWithURL(selURL)

        let vc = SSFotoBrowserViewController(url: s.largePicURLS!, index: indexPath.item)
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func prepareRefresh() {
        refreshControl = SSStatusRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)

    }
    
    private func prepareCell() {
        tableView.registerClass(SSRetweetStatusCell.self, forCellReuseIdentifier: SSStatusCellType.retweet.rawValue)
        tableView.registerClass(SSNormalStatusCell.self, forCellReuseIdentifier: SSStatusCellType.normal.rawValue)
        tableView.estimatedRowHeight = estimatedRowHeight
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.allowsSelection = false
    }
    
    
    private var pullDownFlag = true
    
    func loadData() {
        refreshControl?.beginRefreshing()
        // 确定刷新类型
        var since_id = statuses?.first?.id ?? 0
        var max_id = statuses?.last?.id ?? 0
        since_id = pullDownFlag == true ? since_id : 0
        max_id = pullDownFlag == false ? max_id : 0
        SSStatus.loadUserStatus(since_id, max_id: max_id) { (result, error) -> () in
            self.refreshControl?.endRefreshing()
            self.pullDownFlag = true
            if error != nil  || result == nil {
                print(error)
                return
            }
            let count = result!.count
            print("刷新到了\(count)条数据")
            print("since_id\(since_id)")
            
            if since_id > 0 {
                self.showPopView(count)
            }
            
            if count == 0 {
                return
            }
            
            if since_id > 0 {
                self.statuses = result! + self.statuses!
            } else if max_id > 0 {
                self.statuses! += result!
            } else {
                self.statuses = result!
            }
        }
    }
    
    private func showPopView(count: Int) {
        popView.text = count == 0 ? "暂时没有新微博" : "刷新到\(count)条微博"
        let h: CGFloat = 44
        if popView.layer.animationKeys() != nil {
            return
        }
        UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
            // 要写在任意动画操作之前,
//            UIView.setAnimationRepeatAutoreverses(true)
            self.popView.frame.origin.y = h
            }) { (_) -> Void in
                let time = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                dispatch_after(time, dispatch_get_main_queue(), { () -> Void in
                    UIView.animateWithDuration(1, animations: { () -> Void in
                        self.popView.frame.origin.y = -2 * h
                        }, completion: { (_) -> Void in
                    })
                })
        }
    }
    
    private lazy var popView: UILabel = {
        let h: CGFloat = 44
        let lbl = UILabel(fontColor: UIColor.whiteColor(), fontSize: 17)
        lbl.textAlignment = NSTextAlignment.Center
        lbl.backgroundColor = UIColor.orangeColor()
        lbl.frame = CGRect(x: 0, y: -2 * h, width: UIScreen.mainScreen().bounds.width, height: h)
        self.navigationController?.navigationBar.insertSubview(lbl, atIndex: 0)
        return lbl
    }()
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        let reuseID = status.retweeted_status == nil ? SSStatusCellType.normal : SSStatusCellType.retweet
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseID.rawValue, forIndexPath: indexPath) as! SSStatusCell
        cell.statusCellDelegate = self
        if indexPath.row == (statuses!.count - 1) {
            pullDownFlag = false
            loadData()
        }
        cell.status = status
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses![indexPath.row]
        if status.rowheight != nil {
            return status.rowheight!
        }
        let reuseID = status.retweeted_status == nil ? SSStatusCellType.normal : SSStatusCellType.retweet
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseID.rawValue) as! SSStatusCell
        status.rowheight = cell.getRowHeight(status)
        return status.rowheight!
    }
    
    private lazy var presentView: UIImageView = {
        let pv = UIImageView()
        pv.contentMode = UIViewContentMode.ScaleAspectFill
        pv.clipsToBounds = true
        return pv
    }()
    private var isPresented = false
    private var picView: SSStatusPicView?
    private var presentIndexPath: NSIndexPath?
}

extension SSHomeTableViewController: SSStatusCellDelegate {
    func statusCellDidSelectLinkText(str: String) {
        guard let url = NSURL(string: str) else {
            return
        }
        
        let webViewVc = SSWebViewController(link: url)
        webViewVc.title = "网页"
        webViewVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(webViewVc, animated: true)
    }

}

extension SSHomeTableViewController: UIViewControllerTransitioningDelegate {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}

extension SSHomeTableViewController: UIViewControllerAnimatedTransitioning {
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        if isPresented {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            let fromRect = picView!.cellScreenView(presentIndexPath!)
            let toRect = picView!.cellFullScreenView(presentIndexPath!)
            transitionContext.containerView()?.addSubview(presentView)
            
            presentView.frame = fromRect
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                self.presentView.frame = toRect
                }, completion: { (_) -> Void in
                    self.presentView.removeFromSuperview()
                    transitionContext.containerView()?.addSubview(toView)
                    transitionContext.completeTransition(true)
            })
        } else {
            let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! SSFotoBrowserViewController
            let selIndexPath = fromVC.getIndexPath()
            let toRect = picView!.cellScreenView(selIndexPath)
            // imgView
            let iv = fromVC.getInteractionView()
//            let rect = iv.superview!.convertRect(iv.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
//            print("rect---\(iv.frame)")
//            print("fromVC---\(fromVC.view.frame)")
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
//           iv.frame = rect
            iv.center = fromView.center
            let scale = fromView.transform.a
            iv.transform = CGAffineTransformScale(iv.transform, scale, scale)
//            iv.frame = rect
            
            // bug fix
            if iv.image != nil {
                transitionContext.containerView()?.addSubview(iv)
            }
            fromView.removeFromSuperview()
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                iv.frame = toRect
                }, completion: { (_) -> Void in
                    fromView.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
    }
}
